package repository

import (
	"context"
	"encoding/json"
	"gitee.com/cristiane/micro-mall-search-users-consumer/code"
	"gitee.com/cristiane/micro-mall-search-users-consumer/vars"
	"gitee.com/kelvins-io/common/errcode"
	"gitee.com/kelvins-io/kelvins"
	"github.com/elastic/go-elasticsearch/v7/esapi"
	"strings"
)

func SearchStore(ctx context.Context, index string, docId, body string) (retCode int) {
	retCode = errcode.SUCCESS
	es := vars.ElasticsearchClient
	req := esapi.IndexRequest{
		Index:      index,
		DocumentID: docId,
		Body:       strings.NewReader(body),
		Refresh:    "true",
	}
	res, err := req.Do(ctx, es)
	if err != nil {
		kelvins.ErrLogger.Errorf(ctx, "Elasticsearch getting response err: %v", err)
		retCode = code.ErrESSearch
		return
	}
	defer res.Body.Close()
	if res.IsError() {
		kelvins.ErrLogger.Errorf(ctx, "Elasticsearch [%s] Error indexing document ID=%d", res.Status(), docId)
		retCode = code.ErrESSearch
		return
	} else {
		if res.StatusCode != 200 {
			retCode = code.ErrESSearch
			return
		}
		var r map[string]interface{}
		if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
			kelvins.ErrLogger.Errorf(ctx, "Elasticsearch Error parsing the response body: %s", err)
			retCode = code.ErrESSearch
			return
		} else {
			kelvins.BusinessLogger.Infof(ctx, "Elasticsearch [%s] %s; version=%d ,body: %s", res.Status(), r["result"], int(r["_version"].(float64)), body)
		}
	}
	return
}
